﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CastleOfTheDisillusioned.Location.Maps {
	partial class Map {
		protected void GenerateMap(Cell CurrentCell, List<Type> CellTypes) {
			List<Cell> toextend = new List<Cell>();
			//Console.WriteLine("New Cell - Cell Type: " + CurrentCell.GetType());

			//Try to find someting for every node
			foreach (Node Source in CurrentCell.GetFreeNodes()) {

				//Try every type of cell
				Dictionary<Node, Cell> AllNodeTypes = GetAllNodes(CellTypes, Source.ConnectionType.Opposite());
				//Check every endpoint
				foreach (KeyValuePair<Node, Cell> kvp in AllNodeTypes) {
					Node Dest = kvp.Key;
					Cell cell = kvp.Value;

					if (Source.LinkWith(Dest, this)) {
						Cells.Add(cell);
						toextend.Add(cell);
						//Console.WriteLine("\tGood - Cell Type: " + cell.GetType());
						if (this.Cells.Count > 20) return;
						break;
					} else {
						//Console.WriteLine("\tBad - Cell Type: " + cell.GetType());
					}
				}
			}

			//Console.WriteLine("Done Attempting Cell");

			foreach (Cell cell in toextend) {
				GenerateMap(cell, CellTypes);
			}
		}

		private Dictionary<Node, Cell> GetAllNodes(List<Type> CellTypes, Direction DirectionType){
			Dictionary<Node, Cell> ret = new Dictionary<Node, Cell>();

			//1) Generate Cells
			List<Cell> Cells = new List<Cell>();
			foreach (Type cell in CellTypes) {
				Cells.Add(GetCellInstance(cell));
			}
			Cells = Utilities.Shuffle(Cells);

			//2) Get all the apropriate nodes
			foreach (Cell cell in Cells) {
				List<Node> Nodes = cell.GetFreeNodes(DirectionType);
				foreach (Node n in Nodes) {
					ret.Add(n, cell);
				}
			}

			return ret;
		}

		private Cell GetCellInstance(Type CellType) {
			return CellType.GetConstructor(new Type[] { }).Invoke(new object[] { }) as Cell;
		}
	}
}
